import React, { forwardRef, useImperativeHandle, useState } from 'react';
import AliSvg from '@/components/AliSvg';
import { Empty, Flex, Popconfirm, Progress } from 'antd';
import { formatBits, getUUID, sliceFile } from '@/utils';
import { chunkUploadFun } from '@/services/ant-design-pro/panApi';

interface FilePopconfirmProps {
  updateTable: () => void;
}

const FilePopconfirm = forwardRef((props: FilePopconfirmProps, ref) => {
  const [fileList, setFileList] = useState([]);

  // 显示上传列表
  const showPopconfirm = () => {
    document.getElementById('popconfirmBtn').click();
  };

  // 文件上传方法
  async function uploadFile(nowFileInfo) {
    const fileName = nowFileInfo.fileName; // 文件名称
    const fileSize = nowFileInfo.fileSize; // 文件总大小
    const filePid = nowFileInfo.filePid;
    const file = nowFileInfo.file;
    // 获取切片后的文件切片列表
    const fileSlices = sliceFile(file);

    for (let i = 0; i < fileSlices.length; i++) {
      const postData = new FormData();
      const chunkFile = fileSlices[i];
      postData.append('chunkFile', chunkFile);
      postData.append('fileName', fileName);
      postData.append('fileSize', fileSize);
      postData.append('filePid', filePid);
      postData.append('chunkNum', i + '');
      postData.append('totalChunk', fileSlices.length + '');
      // 上传分片文件
      let res = await chunkUploadFun(postData);
      nowFileInfo.uploadEdSize += chunkFile.size;

      setFileList((prevFileList) =>
        prevFileList.map((item) =>
          item.id === nowFileInfo.id
            ? {
                ...item,
                uploadEdSize: nowFileInfo.uploadEdSize,
                percent: ((nowFileInfo.uploadEdSize / fileSize) * 100).toFixed(0),
              }
            : item,
        ),
      );

      if (res.data === 'SUCCESS') {
        props.updateTable();
        // 判断如果数组长度超过5，则从第6个开始删除
        setFileList((prev) => prev.filter((i) => i.id !== nowFileInfo.id));
      }
    }
  }

  // 追加上传文件列表
  const addFileList = (file, filePid) => {
    let nowFileInfo = {
      id: getUUID(),
      fileName: file.name,
      uploadEdSize: 0, // 已上传大小
      fileSize: file.size, // 文件总大小
      filePid: filePid, // 文件pid
      percent: 0,
      file,
    };
    setFileList((prevFileList) => [nowFileInfo, ...prevFileList]);
    showPopconfirm();
    uploadFile(nowFileInfo);
  };

  // 暴露方法
  useImperativeHandle(ref, () => {
    return {
      showPopconfirm,
      addFileList,
    };
  });

  const UploadList = () => {
    return (
      <div style={{ width: 500, marginTop: 20 }}>
        {fileList.map((item, index) => {
          return (
            <div key={index} className={'upload-list-item'}>
              <Flex justify={'space-between'} align={'center'} gap={15}>
                <div className={'text-ellipsis'}>{item.fileName}</div>
                <div style={{ whiteSpace: 'nowrap' }}>
                  {formatBits(item.uploadEdSize)} / {formatBits(item.fileSize)}
                </div>
              </Flex>
              <Progress strokeWidth={5} percent={item.percent} />
            </div>
          );
        })}

        {fileList.length === 0 && <Empty />}
      </div>
    );
  };

  return (
    <>
      <Popconfirm
        placement="bottomLeft"
        title={
          <Flex gap={5} align={'center'}>
            <div>文件上传列表</div>
            <span style={{ fontSize: 12, color: '#999', fontWeight: 100 }}>
              (只展示当前正在上传文件)
            </span>
          </Flex>
        }
        description={<UploadList />}
        okButtonProps={{ style: { display: 'none' } }} // 隐藏确认按钮
        cancelButtonProps={{ style: { display: 'none' } }} // 隐藏取消按钮
        icon={false}
      >
        <Flex id={'popconfirmBtn'} align={'center'} gap={5} className={'upload-txt'}>
          <AliSvg href={'chuanshu'} size={'1.5em'} />
          <div>上传列表</div>
        </Flex>
      </Popconfirm>
    </>
  );
});

export default FilePopconfirm;
